/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86136
 * Date: 2024-12-01
 * Time: 10:38
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] array = {7,5,3,2,1,5,6,8,3};
        mergeSortNor(array);
        for(int num : array) {
            System.out.print(num + " ");
        }
    }
    public static void mergeSort(int[] array) {
        mergeSortTmp(array,0,array.length-1);
    }

    private static void mergeSortTmp(int[] array, int start, int end) {
        if(start >= end) return;
        int mid = start + (end - start)/2;
        mergeSortTmp(array,start,mid);
        mergeSortTmp(array,mid+1,end);
        merge(array,start,mid,end);
    }

    private static void merge(int[] array, int left,int mid, int right) {
        int[] tmp = new int[right -left + 1];
        int k = 0;
        int s1 = left;
        int e1 = mid;
        int s2 = mid + 1;
        int e2 = right;
        while(s1 <= e1 && s2 <= e2) {
            if(array[s1] < array[s2]) {
                tmp[k++] = array[s1++];
            }else {
                tmp[k++] = array[s2++];
            }
        }
        while(s1 <= e1) {
            tmp[k++] = array[s1++];
        }
        while(s2 <= e2) {
            tmp[k++] = array[s2++];
        }
        for (int i = 0; i < tmp.length; i++) {
            array[i+left] = tmp[i];
        }
    }
    public static void mergeSortNor(int[] array) {
        int gap = 1;
        while(gap < array.length) {
            for (int i = 0; i < array.length; i = i + gap * 2) {
                int left = i;
                int mid = left + gap - 1;
                if (mid >= array.length - 1) {
                    mid = array.length - 1;
                }
                int right = mid + gap;
                if (right >= array.length - 1) {
                    right = array.length - 1;
                }
                merge(array, left, mid, right);
            }
            gap *= 2;
        }

    }
}
